home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: mxsld2.pd.infn.it!LORETI
- From: loreti@mxsld2.pd.infn.it (Maurizio Loreti)
- Subject: Re: Fastest way to computer log(base2) of x?
- X-Nntp-Posting-Host: mxsld2.pd.infn.it
- Message-ID: <DM0AKu.A2H@news.cern.ch>
- Sender: news@news.cern.ch (USENET News System)
- Reply-To: loreti@mxsld2.pd.infn.it
- Organization: I.N.F.N. Padova - CDF/CMS VAXcluster
- References: <4e61iu$p6e@villa.fc.net> <4e6p7t$1n72@cymbal.aix.calpoly.edu> <4e8r54$n8q@ns.RezoNet.NET>,<4e9bl4$3ccp@cymbal.aix.calpoly.edu>
- Date: Tue, 30 Jan 1996 18:12:28 GMT
-
- In article <4e9bl4$3ccp@cymbal.aix.calpoly.edu>, you write:
- >...
- >int left_most_bit (int k) {
- > unsigned posn = 0, mask = 0x80000000;
- >
- > while (!(k & mask)) {
- > mask >>= 1;
- > posn++;
- > }
- > return posn;
- >}
- >+----------------------------------------------------+
-
- A few comments...
-
- - You are right that the overhead of a binary search is not worth
- with, and that a linear search is faster.
- - It is better to make k an unsigned int, as usual when bit operations
- are performed; however that is not essential.
- - 'mask' is initialised to 0x80000000 assuming an int is 32 bits; this
- is not portable. You could #include <limits.h> and set mask to
- ~(UNIT_MAX >> 1) to do that.
- - As it is, the function returns 0 (and not 31) if the MSB bit is set...
- bits are usually numbered starting from 0 (the LSB).
- - As it is, does not handle k=0.
-
- Try the following:
-
- FNALP> type foo.c
- #include <stdio.h>
- #include <limits.h>
-
- int msb(unsigned int);
-
- int main()
- {
- unsigned int array[] = {0x0, 0x1, 0x10, UINT_MAX};
- size_t index;
-
- for (index = 0; index < sizeof(array)/sizeof(array[0]); ++index)
- printf("MSB set in %X is %d\n", array[index], msb(array[index]));
-
- return 0;
- }
-
- int msb( /* Returns the MSB bit set in u, or -1 if u is 0 */
- unsigned int u /* MLO 1996-01-30 */
- ){
- int retval = -1;
-
- while (u) {
- ++retval;
- u >>= 1;
- }
- return retval;
- }
- FNALP> cc foo
- FNALP> link foo
- FNALP> run foo
- MSB set in 0 is -1
- MSB set in 1 is 0
- MSB set in 10 is 4
- MSB set in FFFFFFFF is 31
-
- Hope that helps... Comments welcome.
- --
- Maurizio Loreti http://mvxpd5.pd.infn.it/wwwcdf/mlo.html
- Un. of Padova, Dept. of Physics - Padova, Italy loreti@padova.infn.it
-